package utils;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author tongchen
 * @create 2023-04-02 19:50
 */
public class DBUtil {
    //获取数据源
    private static DataSource dataSource;
    private static String url="jdbc:mysql://localhost:3307/exer2?characterEncoding=utf8&useSSL=false";
    private static String root="root";
    private  static String password="abc123";
    //实现单例模式（私有化构造方法）

    private DBUtil() {
    }
    //通过静态代码块实现连接对象的创建
    static {
        MysqlDataSource mysqlDataSource = new MysqlDataSource();
        mysqlDataSource.setURL(url);
        mysqlDataSource.setUser(root);
        mysqlDataSource.setPassword(password);
        dataSource=mysqlDataSource;
    }

    //建立连接
    //获取连接对象
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }
    //关闭连接
    public static void closeResources(Connection connection, PreparedStatement statement, ResultSet resultSet){
        //一定要一个一个的关闭，避免因为某个异常其他资源没有关闭
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
